package com.wwwarehouse.usercenter.fragment.register;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CircleImageView;
import com.wwwarehouse.common.custom_widget.ClearEditText;
import com.wwwarehouse.common.custom_widget.address_dialog.DialogSelectAddressUpdate;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.custom_widget.textinput.TextInputLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.custom_widget.time_pick.DatePickerDialog;
import com.wwwarehouse.common.db.DbUtils;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tripartite_widget.faceprint.FaceUtil;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.common.UserCenterCommon;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.usercenter.R.id.et_name;
import static com.wwwarehouse.usercenter.R.id.et_number;

/**
 * 实名认证
 * Created by xiaoke.ni on 2017/8/11.
 */
public class RCRealNameAuthStep2Fragment extends RegisterCardBaseFragment implements View.OnClickListener, TextWatcher {
    private View            mRootView;
    private EditText        mNameTxt;
    private CircleImageView mHeadImg;
    private ClearEditText   mNumberTxt;
    private RelativeLayout  mBirthdayLayout;
    private TextView        mBirthdayTxt;
    private RelativeLayout  mExpirationLayout;
    private TextView        mExpirationTxt;

    private Button mCompleteBtn;

    private static final int REQUEST_CHECK_ID_CARD = 0;
    private TextView            mTvNation;
    private TextView            mTvPlace;
    private LinearLayout        mLlNation;
    private LinearLayout        mLlPlace;
    private LinearLayout        mLlBirthday;
    private LinearLayout        mLlExpiration;
    private List<String>        mNationsList;
    private RadioButton         mRbFemale;
    private RadioButton         mRbMale;
    private RelativeLayout      mRlElse;
    private VirtualKeyboardView mIdKeyBoard;
    private TextInputLayout     mTilName;
    private TextInputLayout     mTilNum;
    private String              mIdCard;
    private int                 mYear;
    private int                 mMonth;
    private int                 mDay;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_rc_real_name_auth_step2, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initEvent();
    }

    private Bitmap mImage = null;

    private void initView() {
        Calendar c = Calendar.getInstance();//
        // 获取当前年份
        mYear = c.get(Calendar.YEAR);
        // 获取当前月份
        mMonth = c.get(Calendar.MONTH) + 1;
        // 获取当日期
        mDay = c.get(Calendar.DAY_OF_MONTH);

        mIdKeyBoard = findView(mRootView, R.id.idnumber);
        mIdKeyBoard.setOnConfirmListener(new VirtualKeyboardView.OnConfirmListener() {
            @Override
            public void confirm() {
                mIdKeyBoard.setVisibility(View.INVISIBLE);
            }
        });
        mRlElse = findView(mRootView, R.id.rl_else);
        mRlElse.setOnClickListener(this);
        mTilName = findView(mRootView, R.id.til_name);
        mNameTxt = findView(mRootView, et_name);//姓名
        mNameTxt.setOnClickListener(this);
        mHeadImg = findView(mRootView, R.id.iv_head);//头像
        mRbFemale = findView(mRootView, R.id.rb_female);
        mRbFemale.setOnClickListener(this);
        mRbMale = findView(mRootView, R.id.rb_male);
        mRbMale.setOnClickListener(this);
        //        BaseApplication.getApplicationInstance().displayRoundImgPixel("drawable://" + R.drawable.laucher_logo, mHeadImg, 160);
        mTvNation = findView(mRootView, R.id.tv_nation);//民族
        mLlNation = findView(mRootView, R.id.ll_nation);//选民族的布局
        mTvPlace = findView(mRootView, R.id.tv_place);//籍贯
        mLlPlace = findView(mRootView, R.id.ll_place);//选择籍贯的布局
        mTilNum = findView(mRootView, R.id.til_number);
        mNumberTxt = findView(mRootView, R.id.et_number);//身份证号码
        mNumberTxt.addTextChangedListener(this);
        hideSystemKeyboard(mNumberTxt);

        mNumberTxt.setOnClickListener(this);
        mBirthdayLayout = findView(mRootView, R.id.rl_birthday);
        mBirthdayTxt = findView(mRootView, R.id.tv_birthday);//出生年月
        mLlBirthday = findView(mRootView, R.id.ll_birthday);//选择出生年月的布局
        mExpirationLayout = findView(mRootView, R.id.rl_expiration);
        mExpirationTxt = findView(mRootView, R.id.tv_expiration);//有效期限
        mLlExpiration = findView(mRootView, R.id.ll_expiration);//选择有效期限的布局
        mCompleteBtn = findView(mRootView, R.id.btn_complete);

        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getPersonName())) {
            mNameTxt.setText(UserCenterCommon.getInstance().getPersonName());
        }

        if (!TextUtils.isEmpty(mNameTxt.getText())) {
            mTilName.updateLabelState();
        }
        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getNation())) {
            mTvNation.setText(UserCenterCommon.getInstance().getNation());
        }
        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getBirthPlace())) {
            mTvPlace.setText(UserCenterCommon.getInstance().getBirthPlace());
        }

        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getIdCard())) {
            if (UserCenterCommon.getInstance().getIdCard().length() == 15 || UserCenterCommon.getInstance().getIdCard().length() == 18) {
                mNumberTxt.setText(UserCenterCommon.getInstance().getIdCard());
            }
        }

        if (!TextUtils.isEmpty(mNumberTxt.getText())) {
            mTilNum.updateLabelState();
        }
        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getBirthday())&& UserCenterCommon.getInstance().getBirthday().length() >= 10) {
            mBirthdayTxt.setText(UserCenterCommon.getInstance().getBirthday().substring(0, 10));
        }

        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getExpirationDate()) && UserCenterCommon.getInstance().getExpirationDate().length() >= 21) {
            String expirationDate = UserCenterCommon.getInstance().getExpirationDate();
            String substring = expirationDate.substring(11, 21);
            String[] expiration = substring.split("[.]");
            int year = Integer.parseInt(expiration[0]);
            int month = Integer.parseInt(expiration[1]);
            int day = Integer.parseInt(expiration[2]);
            if (year < mYear) {
                mExpirationTxt.setText(mYear + "-" + mMonth + "-" + mDay);
            } else if (month < mMonth) {
                mExpirationTxt.setText(mYear + "-" + mMonth + "-" + mDay);
            } else if (day < mDay) {
                mExpirationTxt.setText(mYear + "-" + mMonth + "-" + mDay);
            } else {
                String expirationDateReplaceAll = substring.replaceAll("[.]", "-");
                mExpirationTxt.setText(expirationDateReplaceAll);
            }
        } else {
            mExpirationTxt.setText(mYear + "-" + mMonth + "-" + mDay);
        }




        if (UserCenterCommon.getInstance().getPersonSex().equals("男")) {
            mRbMale.setChecked(true);
        } else if (UserCenterCommon.getInstance().getPersonSex().equals("女")) {
            mRbFemale.setChecked(true);
        }

        if (!TextUtils.isEmpty(UserCenterCommon.getInstance().getCutHead())) {
            //获取先前裁剪存好的路径
            String fileSrc = UserCenterCommon.getInstance().getCutHead();
            // 获取图片的宽和高
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            mImage = BitmapFactory.decodeFile(fileSrc, options);

            // 压缩图片
            options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
                    (double) options.outWidth / 1024f,
                    (double) options.outHeight / 1024f)));
            options.inJustDecodeBounds = false;
            mImage = BitmapFactory.decodeFile(fileSrc, options);
            // 若mImageBitmap为空则图片信息不能正常获取
            if (null == mImage) {
                //                ToastUtils.showToast("图片信息无法正常获取！");
                return;
            }
            // 部分手机会对图片做旋转，这里检测旋转角度
            int degree = FaceUtil.readPictureDegree(fileSrc);
            if (degree != 0) {
                // 把图片旋转为正的方向
                mImage = FaceUtil.rotateImage(degree, mImage);
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //可根据流量及网络状况对图片进行压缩
            mImage.compress(Bitmap.CompressFormat.JPEG, 80, baos);

            mHeadImg.setImageBitmap(mImage);
        }

    }

    private void hideSystemKeyboard(EditText... mNumber) {
        for (int i = 0; i < mNumber.length; i++) {
            // 设置不调用系统键盘
            if (android.os.Build.VERSION.SDK_INT <= 10) {
                mNumber[i].setInputType(InputType.TYPE_NULL);
            } else {
                mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

                Class<EditText> clazz = EditText.class;
                Method method;

                try {
                    method = clazz.getMethod("setShowSoftInputOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    method = clazz.getMethod("setSoftInputShownOnFocus", boolean.class);
                    method.setAccessible(true);
                    method.invoke(mNumber[i], false);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof RCRealNameAuthStep2Fragment) {
            mActivity.setTitle(R.string.real_name_auth);
        }
    }

    @Override
    public void requestDatas() {
    }

    private void initEvent() {
        mNationsList = DbUtils.getNations(mActivity);
        mLlNation.setOnClickListener(this);
        mLlPlace.setOnClickListener(this);
        mLlBirthday.setOnClickListener(this);
        mLlExpiration.setOnClickListener(this);

        mCompleteBtn.setOnClickListener(this);
        mNumberTxt.setOnMyFocusChangeListener(new ClearEditText.onMyFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                int id = view.getId();
                if (id == et_number && b) {
                    if (mIdKeyBoard.getVisibility() != View.VISIBLE) {
                        mIdKeyBoard.setVisibility(View.VISIBLE);
                        hideSoftKeyBoard(mNameTxt);
                    }
                    mIdKeyBoard.setEditText((ClearEditText) view);
                } else {
                    if (mIdKeyBoard.getVisibility() == View.VISIBLE) {
                        mIdKeyBoard.setVisibility(View.INVISIBLE);
                    }

                }
            }
        });



    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i != R.id.et_name) {
            hideSoftKeyBoard(v);
        }
        if (i != R.id.et_number) {
            if (mIdKeyBoard.getVisibility() == View.VISIBLE) {
                mIdKeyBoard.setVisibility(View.INVISIBLE);
            }

        }
        if (i == R.id.et_number) {
            mIdKeyBoard.setVisibility(View.VISIBLE);

        }
        if (i == R.id.ll_nation) {
            new ChoosePickerDialog.Builder(mActivity).setTitle(mActivity.getResources().getString(R.string.choose_nation)).setData(mNationsList).
                    setSelection(mTvNation.getText().toString().trim()).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                @Override
                public void onSelected(String s, int i) {
                    mTvNation.setText(s);
                }

                @Override
                public void onCancel() {

                }
            }).create().show();

        } else if (i == R.id.ll_place) {
            DialogSelectAddressUpdate dialogSelectAddressUpdate = new DialogSelectAddressUpdate(mActivity,true);
            dialogSelectAddressUpdate.setListener(new DialogSelectAddressUpdate.AddressListener() {
                @Override
                public void setAddress(String province, String city, String district, String street) {
                    mTvPlace.setText(province + city + district + street);
                }
            });
            dialogSelectAddressUpdate.setCancelable(true);
            dialogSelectAddressUpdate.show();

        } else if (i == R.id.ll_birthday) {
            String[] birthday = mBirthdayTxt.getText().toString().split("[-]");
            for (int j = 0; j < birthday.length; j++) {
                LogUtils.showLog(birthday[j]);
            }
            int yearSelect=Integer.parseInt(birthday[0]+"");
            int monSelect=Integer.parseInt(birthday[1]+"");
            int daySelect=Integer.parseInt(birthday[2]+"");
            new DatePickerDialog.Builder(mActivity).setSelectYear(yearSelect-1).setSelectMonth(monSelect-1).setSelectDay(daySelect-1).setMinYear(1930).setMinMonth(1).setMinDay(1).setMaxYear(mYear).setMaxMonth(mMonth).setMaxDay(mDay).setTitle(getString(R.string.pls_choose_date))
                    .setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {
                        @Override
                        public void onDateSelected(String s) {
                            mBirthdayTxt.setText(s);
                        }

                        @Override
                        public void onCancel() {

                        }
                    }).create().show();

        } else if (i == R.id.ll_expiration) {
            String[] expiration = mExpirationTxt.getText().toString().split("[-]");
            int yearSelect=Integer.parseInt(expiration[0].toString());
            int monSelect=Integer.parseInt(expiration[1].toString());
            int daySelect=Integer.parseInt(expiration[2].toString());
            new DatePickerDialog.Builder(mActivity).setSelectYear(yearSelect-1).setSelectMonth(monSelect-1).setSelectDay(daySelect-1).setMinYear(mYear).setMinMonth(mMonth).setMinDay(mDay).setMaxYear(mYear+50).setMaxMonth(12).setMaxDay(31).setTitle(getString(R.string.pls_choose_date)).
                    setOnDateSelectedListener(new DatePickerDialog.OnDateSelectedListener() {
                        @Override
                        public void onDateSelected(String s) {
                            mExpirationTxt.setText(s);
                        }

                        @Override
                        public void onCancel() {

                        }
                    }).create().show();

        } else if (i == R.id.btn_complete) {
            if (!TextUtils.isEmpty(mNameTxt.getText().toString().trim()) && !TextUtils.isEmpty(mTvNation.getText().toString().trim()) && !TextUtils.isEmpty(mTvPlace.getText().toString().trim())
                    && !TextUtils.isEmpty(mNumberTxt.getText().toString().trim()) && !TextUtils.isEmpty(mBirthdayTxt.getText().toString().trim()) && !TextUtils.isEmpty(mExpirationTxt.getText().toString().trim())) {
                checkIdCard();
            } else if (TextUtils.isEmpty(mNameTxt.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.name_no));
            } else if (TextUtils.isEmpty(mTvNation.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.mingzu));
            } else if (TextUtils.isEmpty(mTvPlace.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.jiguan));
            } else if (TextUtils.isEmpty(mNumberTxt.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.shenfenzheng));
            } else if (TextUtils.isEmpty(mBirthdayTxt.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.chengsheng));
            } else if (TextUtils.isEmpty(mExpirationTxt.getText().toString().trim())) {
                toast(mActivity.getResources().getString(R.string.youxiaoqi));
            }
            /*<string name="name_no">姓名不能为空</string>
    <string name="mingzu">请选择民族</string>
    <string name="jiguan">请选择籍贯</string>
    <string name="shenfenzheng">请输入身份证号</string>
    <string name="chengsheng">请选择出生日期</string>
    <string name="youxiaoqi">请选择身份证有效日期</string>*/

        } else if (i == R.id.rl_else) {
            hideSoftKeyBoard(v);
            if (mIdKeyBoard.getVisibility() == View.VISIBLE) {
                mIdKeyBoard.setVisibility(View.INVISIBLE);
            }

        }
    }

    private void checkIdCard() {
        showProgressDialog(getString(R.string.submiting));

        Map<String,String> map = new HashMap();
        map.put("name", mNameTxt.getText().toString().trim());
        String trim = mNumberTxt.getText().toString().trim();
        mIdCard = trim.replaceAll(" ", "").toString().trim();
        map.put("idCard", mIdCard);

        NoHttpUtils.httpPost(UserCenterConstant.URL_CHECK_ID_CARD, map, mOnResponseListener, REQUEST_CHECK_ID_CARD);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_CHECK_ID_CARD:
                    if ("0".equals(commonClass.getCode())) {
                        //                        sp.putBooleanValue("isRealNameAuth",true);
                        EventBus.getDefault().post("RCRealNameAuthStep2Fragment");
                        UserCenterCommon.getInstance().setExpirationDate(mExpirationTxt.getText().toString().trim() + " 00:00:00");
                        UserCenterCommon.getInstance().setPersonName(mNameTxt.getText().toString());
                        UserCenterCommon.getInstance().setNation(mTvNation.getText().toString());
                        UserCenterCommon.getInstance().setBirthPlace(mTvPlace.getText().toString());
                        UserCenterCommon.getInstance().setIdCard(mIdCard);
                        UserCenterCommon.getInstance().setBirthday(mBirthdayTxt.getText().toString() + " 00:00:00");
                        if (mRbFemale.isChecked()) {
                            UserCenterCommon.getInstance().setPersonSex("女");
                        }
                        if (mRbMale.isChecked()) {
                            UserCenterCommon.getInstance().setPersonSex("男");
                        }

                        //身份证验证成功
                        popFragment();
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            toast(result);
        }

        @Override
        public void onFinish(int what) {
            dismissProgressDialog();
        }
    };

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s == null || s.length() == 0)
            return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 6 && i != 11 && i != 16 && i != 21 && s.charAt(i) == ' ') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 7 || sb.length() == 12 || sb.length() == 17||sb.length()==22) && sb.charAt(sb.length() - 1) != ' ') {
                    sb.insert(sb.length() - 1, ' ');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == ' ') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            mNumberTxt.setText(sb.toString());
            mNumberTxt.setSelection(sb.length());
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        hideSoftKeyBoard(mNameTxt);
        if (mIdKeyBoard.getVisibility() == View.VISIBLE) {
            mIdKeyBoard.setVisibility(View.INVISIBLE);
        }
    }
}
